﻿using CRMModel;
using FRMS.BUS.ServerPlatform;
using FRMS.DAL;
using FRMS.Model;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.X9;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;

namespace FRMS.BUS
{
    public class OwnerBUS
    {
        public ResponseMessage AddOwner(OwnerInfo ownerInfo, string path)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerDAL da = new OwnerDAL();
            if (string.IsNullOrEmpty(ownerInfo.UUID))
            {
                ownerInfo.UUID = GetUUID(ownerInfo.projectID);
            }

            if (string.IsNullOrEmpty(ownerInfo.CardNO))
            {
                ownerInfo.CardNO = GetCardNo();
            }
            if (!string.IsNullOrEmpty(ownerInfo.PicturePath))
            {
                ownerInfo.PicturePath = UpdatePath(ownerInfo.EmployeeNo, ownerInfo.PicturePath, path);
            }

            //如果是副卡
            if (ownerInfo.ParentID != 0)
            {
                int ownerid = da.AddSlaveOwner(ownerInfo);
                VoucherDAL voucherDAL = new VoucherDAL();
                VoucherInfo voucher = new VoucherInfo();
                voucher.OwnerID = ownerInfo.ParentID;
                List<VoucherInfo> list = voucherDAL.QueryVoucherList(voucher);

                foreach (var item in list)
                {
                    item.OwnerID = ownerid;
                    item.EffectiveStarttime = Convert.ToDateTime(item.EffectiveStarttime).ToString("yyyy-MM-dd HH:mm:ss");
                    item.EffectiveEndtime = Convert.ToDateTime(item.EffectiveEndtime).ToString("yyyy-MM-dd HH:mm:ss");
                    bool res = voucherDAL.AddVoucher(item);
                    if (!res)
                    {
                        message.errcode = 1;
                        message.data = "副卡凭证绑定失败";
                        return message;
                    }
                }
            }
            else
            {
                bool result = da.AddOwner(ownerInfo);
                if (result)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "新增业主信息失败";
                }
            }

            return message;
        }

        public ResponseMessage ImportOwner(OwnerInfo ownerInfo, VoucherInfo voucher, string str_base64, string webRootPath)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerDAL da = new OwnerDAL();
            if (string.IsNullOrEmpty(ownerInfo.UUID))
            {
                ownerInfo.UUID = GetUUID(ownerInfo.projectID);
            }
            if (string.IsNullOrEmpty(ownerInfo.CardNO))
            {
                ownerInfo.VirtualCard = 1;
                ownerInfo.CardNO = GetCardNo();
            }
            else
            {
                ownerInfo.VirtualCard = 0;
            }
            ownerInfo.PicturePath = Base64ToImage(str_base64, webRootPath);

            int ownerid = da.ImportOwner(ownerInfo);

            if (ownerid > 0)
            {
                voucher.OwnerID = ownerid;
                VoucherBUS voucherBUS = new VoucherBUS();
                bool result = voucherBUS.ImportVoucher(voucher);
                if (!result)
                {
                    message.errcode = 1;
                }
            }
            else
            {
                message.errcode = 1;
            }

            return message;
        }

        public ResponseMessage AddProperty(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerDAL da = new OwnerDAL();
            int cardshow = 0;
            int picshow = 0;
            if (string.IsNullOrEmpty(ownerInfo.UUID))
            {
                ownerInfo.UUID = GetUUID(ownerInfo.projectID);
            }

            if (string.IsNullOrEmpty(ownerInfo.CardNO))
            {
                ownerInfo.CardNO = GetCardNo();
            }
            else
            {
                cardshow = 1;
            }

            if (!string.IsNullOrEmpty(ownerInfo.PicturePath))
            {
                cardshow = 1;
                picshow = 1;
            }

            DeviceDAL deviceDAL = new DeviceDAL();
            DeviceInfo deviceInfo = new DeviceInfo();
            List<DeviceInfo> list = deviceDAL.QueryDeviceInfo(deviceInfo);
            int proid = da.AddProperty(ownerInfo);
            if (proid > 0)
            {
                message.errcode = 0;
                /*foreach (var item in list)
                {
                    ModbusRtu modbus = new ModbusRtu();
                    VoucherDAL voucherDAL = new VoucherDAL();
                    VoucherInfo voucher = new VoucherInfo();
                    voucher.OwnerID = proid;
                    voucher.AuthorizedFloor = item.FloorInfo;
                    voucher.AuthData = modbus.GetCallAdminCmd(ownerInfo.UUID);
                    voucher.projectID = item.projectID;
                    voucher.DeviceID = item.ID;
                    voucher.EffectiveStarttime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    voucher.EffectiveEndtime = Convert.ToDateTime(ownerInfo.MaxTime).ToString("yyyy-MM-dd HH:mm:ss");
                    voucher.CardShow = cardshow;
                    voucher.PicShow = picshow;
                    voucherDAL.AddVoucher(voucher);
                }*/
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "物业新增失败";
            }


            return message;
        }

        public ResponseMessage EditOwner(OwnerInfo ownerInfo, string path)
        {
            ResponseMessage message = new ResponseMessage();
            VoucherDAL voucherDAL = new VoucherDAL();
            OwnerDAL da = new OwnerDAL();
            OwnerInfo info = da.LoadOwnerInfo(ownerInfo.ID);

            if (info.PicturePath != ownerInfo.PicturePath)
            {
                ownerInfo.PicturePath = UpdatePath(ownerInfo.EmployeeNo, ownerInfo.PicturePath, path);
            }

            if (string.IsNullOrEmpty(ownerInfo.CardNO))
            {
                ownerInfo.CardNO = GetCardNo();
            }
            VoucherInfo v_info = new VoucherInfo();
            v_info.OwnerID = ownerInfo.ID;
            List<VoucherInfo> list = voucherDAL.QueryVoucherList(v_info);
            if (list.Count == 0)
            {

                bool result = da.UpdateOwner(ownerInfo);
                if (result)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "修改业主信息失败";
                }
            }
            else
            {
                VoucherInfo voucher = new VoucherInfo();
                bool CarduploadFlag = false;
                bool PicuploadFlag = false;
                bool Lssuestate = false;
                if (ownerInfo.CardNO != info.CardNO)
                {
                    CarduploadFlag = true;
                    Lssuestate = true;
                }
                if (ownerInfo.PicturePath != info.PicturePath)
                {
                    PicuploadFlag = true;
                    Lssuestate = true;
                }
                if (ownerInfo.VirtualCard != info.VirtualCard)
                {
                    Lssuestate = true;
                    ModbusRtu modbusRtu = new ModbusRtu();
                    if (ownerInfo.VirtualCard == 2)
                    {
                        voucher.AuthData = modbusRtu.GetLiftStateCmd(1);
                    }
                    else if (ownerInfo.VirtualCard == 3)
                    {
                        voucher.AuthData = voucher.AuthData = modbusRtu.GetLiftStateCmd(0);
                    }
                }

                if (ownerInfo.OwnerType == 2 && Convert.ToDateTime(ownerInfo.MaxTime).ToString("yyyy-MM-dd HH:mm:ss") != info.MaxTime)
                {

                    Lssuestate = true;
                    voucher.EffectiveEndtime = Convert.ToDateTime("2038-01-01").ToString("yyyy-MM-dd HH:mm:ss");
                }
                voucher.OwnerID = info.ID;
                voucher.OwnerType = info.OwnerType;
                bool result1 = da.UpdateAllByOwnerid(voucher, CarduploadFlag, PicuploadFlag, Lssuestate);
                if (result1)
                {
                    bool result = da.UpdateOwner(ownerInfo);
                    if (result)
                    {
                        message.errcode = 0;
                    }
                    else
                    {
                        message.errcode = 1;
                        message.errmsg = "修改业主信息失败";
                    }
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "修改业主信息失败";
                }
            }


            return message;
        }

        public ResponseMessage DeleteOwner(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerDAL da = new OwnerDAL();

            VoucherDAL voucherDAL = new VoucherDAL();
            VoucherInfo info = new VoucherInfo();
            info.OwnerID = ownerInfo.ID;
            List<VoucherInfo> list = voucherDAL.QueryVoucherList(info);
            if (list.Count > 0)
            {
                string failinfo = string.Empty;
                VoucherBUS voucherBUS = new VoucherBUS();
                foreach (var item in list)
                {
                    if (item.DeviceState == "在线")
                    {
                        if (item.Flag == 1)
                        {
                            JLLssueinfoDel info1 = voucherBUS.JLVoucherDel(item);
                            string re = voucherBUS.HttpClientPost("http://" + item.DeviceIP + ":8011/Request", info1);
                            JLLssueinfoReturn jLLssueinfoReturn = JsonConvert.DeserializeObject<JLLssueinfoReturn>(re);
                            if (jLLssueinfoReturn.Name == "personListResponse" && jLLssueinfoReturn.Code == 1)
                            {
                                message = voucherBUS.DelVoucher(item);
                                if (message.errcode == 1)
                                {
                                    failinfo += item.DeviceName + ",";
                                }
                            }
                            else if (jLLssueinfoReturn.Name == "personListResponse" && jLLssueinfoReturn.Data.Result == -21 && jLLssueinfoReturn.Code == 1110)
                            {
                                message = voucherBUS.DelVoucher(item);
                                if (message.errcode == 1)
                                {
                                    failinfo += item.DeviceName + ",";
                                }
                            }
                            else
                            {
                                failinfo += item.DeviceName + ",";
                            }
                        }
                        else
                        {
                            message = voucherBUS.DelVoucher(item);
                            if (message.errcode == 1)
                            {
                                failinfo += item.DeviceName + ",";
                            }
                        }
                    }
                    else
                    {
                        message = voucherBUS.DelVoucher(item);
                        if (message.errcode == 1)
                        {
                            failinfo += item.DeviceName + ",";
                        }
                    }
                }
                if (failinfo.Length > 0)
                {
                    message.errcode = 1;
                    message.errmsg = "删除失败，设备凭证" + failinfo.Substring(0, failinfo.Length - 1) + "删除失败";
                }
                else
                {
                    bool result = da.DeleteOwner(ownerInfo);
                    if (result)
                    {
                        message.errcode = 0;
                    }
                    else
                    {
                        message.errcode = 1;
                        message.errmsg = "删除业主信息失败";
                    }
                }
            }
            else
            {
                bool result = da.DeleteOwner(ownerInfo);
                if (result)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "删除业主信息失败";
                }
            }



            return message;
        }

        public ResponseMessage QueryOwner(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerDAL da = new OwnerDAL();
            message.errcode = 0;
            message.data = da.QueryOwner(ownerInfo);
            message.total = da.QueryOwnerCount(ownerInfo);

            return message;
        }

        public ResponseMessage QueryOwneList(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerDAL da = new OwnerDAL();
            message.errcode = 0;
            message.data = da.QueryOwnerList(ownerInfo);
            message.total = da.QueryOwnerListCount(ownerInfo);

            return message;
        }

        public ResponseMessage LoadOwner(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerDAL da = new OwnerDAL();
            message.errcode = 0;
            message.data = da.LoadOwnerInfo(ownerInfo.ID);

            return message;
        }

        public ResponseMessage QueryOwnerType()
        {
            ResponseMessage message = new ResponseMessage();
            OwnerDAL da = new OwnerDAL();
            message.errcode = 0;
            message.data = da.QueryOwnerMasterType();

            return message;
        }

        public ResponseMessage QuerySlaveType()
        {
            ResponseMessage message = new ResponseMessage();
            OwnerDAL da = new OwnerDAL();
            message.errcode = 0;
            message.data = da.QueryOwnerSlaveType();

            return message;
        }

        public string GetUUID(int projectid)
        {
            string uuid = string.Empty;
            bool result = true;
            OwnerDAL da = new OwnerDAL();
            ProjectDAL projectDAL = new ProjectDAL();
            ProjectInfo projectInfo = projectDAL.LoadProject(projectid);
            while (result)
            {
                Random random = new Random();
                int randomid = random.Next(1, 999999);
                uuid = Convert.ToInt32(projectInfo.project_code).ToString("X").PadLeft(2, '0') + randomid.ToString().PadLeft(6, '0');
                result = da.CheckUUID(uuid);
            }
            return uuid;
        }

        public string GetCardNo()
        {
            string cardno = string.Empty;
            bool result = true;
            OwnerDAL da = new OwnerDAL();
            while (result)
            {
                Random random = new Random();

                int num = random.Next(0, 9999);
                cardno = DateTime.Now.ToString("yyMMdd") + num.ToString().PadLeft(4, '0');
                result = da.CheckCard(cardno);
            }
            return cardno;
        }

        public ResponseMessage CopyOwner(int ownerid, int roomid, string path)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerDAL da = new OwnerDAL();
            string errmsg = string.Empty;
            int pid = da.CopyOwner(ownerid, roomid);
            if (pid > 0)
            {
                List<OwnerInfo> list = da.QueryOwnerByPID(ownerid);
                foreach (var item in list)
                {
                    item.ParentID = pid;
                    item.PicturePath = UpdatePath(item.EmployeeNo, item.PicturePath, path);
                    bool result = da.AddOwner(item);

                    if (!result)
                    {
                        errmsg += item.OwnerName + ",";
                    }
                }
                if (!string.IsNullOrEmpty(errmsg))
                {
                    message.errcode = 1;
                    message.errmsg = errmsg.TrimEnd(',') + "副卡复制失败";
                }
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "复制卡失败";
            }

            return message;
        }

        public string Base64ToImage(string dataURL, string webRootPath)
        {
            try
            {
                dataURL = dataURL.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
                byte[] bytes = Convert.FromBase64String(dataURL);
                MemoryStream memStream = new MemoryStream(bytes);
                Image mImage = Image.FromStream(memStream);

                Bitmap bp = new Bitmap(mImage);

                String Tpath = "/img/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string FilePath = webRootPath + "/wwwroot" + Tpath;
                DirectoryInfo di = new DirectoryInfo(FilePath);


                if (!di.Exists) { di.Create(); }

                using (FileStream fs = File.Create(FilePath + FileName + ".jpg"))
                {
                    // 复制文件
                    bp.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
                    // 清空缓冲区数据
                    bp.Dispose();
                    fs.Flush();
                    fs.Close();
                }

                return Tpath + FileName + ".jpg";//返回相对路径 

            }
            catch (Exception e)
            {
                return "";
            }
        }

        public ReturnMessage AddSyncOwner(SyncOwnerInfo ownerInfo)
        {
            ReturnMessage message = new ReturnMessage();
            OwnerDAL da = new OwnerDAL();
            ProjectDAL projectDAL = new ProjectDAL();
            int projectID = projectDAL.QueryProjectID(ownerInfo.projectcode);
            if (projectID > 0)
            {
                int roomid = projectDAL.QueryRoomID(projectID, ownerInfo.RoomID);
                if (roomid > 0)
                {
                    if (string.IsNullOrEmpty(ownerInfo.UUID))
                    {
                        string UUID = GetUUID(projectID);

                        int proid = da.AddSyncOwner(ownerInfo, projectID, UUID);
                        if (proid > 0)
                        {
                            message.errcode = 0;
                            SyncOwnerInfo sync = new SyncOwnerInfo();
                            sync = ownerInfo;
                            sync.UUID = UUID;
                            message.data = sync;
                        }
                        else
                        {
                            message.errcode = 1;
                            message.errmsg = "同步业主信息失败";
                        }
                    }
                    else
                    {
                        bool re = da.UpdateSyncOwner(ownerInfo, projectID);
                        if (re)
                        {
                            message.errcode = 0;
                            SyncOwnerInfo sync = new SyncOwnerInfo();
                            sync = ownerInfo;
                            message.data = sync;
                        }
                        else
                        {
                            message.errcode = 1;
                            message.errmsg = "更新业主信息失败";
                        }
                    }
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "该房间不存在";
                }
            }
            else
            {
                message.errcode = 1;
                message.errmsg = "该项目码不存在";
            }

            return message;
        }

        public ReturnMessage DeleteSyncOwner(DeleteSyncOwnerInfo ownerInfo)
        {
            ReturnMessage message = new ReturnMessage();
            OwnerDAL da = new OwnerDAL();
            ProjectDAL projectDAL = new ProjectDAL();
            int projectID = projectDAL.QueryProjectID(ownerInfo.projectcode);
            if (projectID > 0)
            {
                List<OwnerInfo> list = da.QuerySyncOwner(projectID, ownerInfo.UUID);
                if (list.Count > 0)
                {
                    bool result = da.DeleteSyncOwner(ownerInfo.UUID, projectID);
                    if (result)
                    {
                        message.errcode = 0;
                    }
                    else
                    {
                        message.errcode = 1;
                        message.errmsg = "删除业主失败";
                    }
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "业主不存在";
                }

            }
            else
            {
                message.errcode = 1;
                message.errmsg = "该项目码不存在";
            }
            return message;
        }

        public string UpdatePath(string uuid, string file, string webRootPath)
        {
            string oldpath = string.Empty;
            string newpath = string.Empty;
            string type = Path.GetExtension(file);
            string originalFileName = webRootPath + "/wwwroot" + file;
            string newFileName = webRootPath + "/wwwroot/img/" + uuid + type;


            // 确保目标文件名不存在，否则会抛出异常
            if (File.Exists(newFileName))
            {
                File.Delete(newFileName);
            }

            // 修改文件名称
            System.IO.Directory.Move(originalFileName, newFileName);

            return "/img/" + uuid + type;
        }

        public ResponseMessage MultipleVoucher(MultipleVoucher multipleVoucher,int projectid)
        {
            ResponseMessage message = new ResponseMessage();
            ModbusRtu modbus = new ModbusRtu();
            string[] device_arr = multipleVoucher.deviceids.Split(',');
            string[] owner_arr = multipleVoucher.ownerids.Split(',');
            VoucherDAL voucherDAL = new VoucherDAL();
            for (int m = 0; m < owner_arr.Length; m++)
            {
                OwnerDAL ownerDAL = new OwnerDAL();
                OwnerInfo ownerInfo = ownerDAL.LoadOwnerInfo(Convert.ToInt32(owner_arr[m]));
                string AuthData = modbus.GetCallAdminCmd(ownerInfo.UUID);
                for (int i = 0; i < device_arr.Length; i++)
                {
                    VoucherInfo voucherInfo = new VoucherInfo();
                    voucherInfo.OwnerID = Convert.ToInt32(owner_arr[m]);
                    voucherInfo.DeviceID = Convert.ToInt32(device_arr[i]);
                    voucherInfo.projectID = projectid;
                    voucherInfo.EffectiveEndtime = Convert.ToDateTime(multipleVoucher.EffectiveEndtime).ToString("yyyy-MM-dd HH:mm:ss");
                    voucherInfo.EffectiveStarttime = Convert.ToDateTime(multipleVoucher.EffectiveStarttime).ToString("yyyy-MM-dd HH:mm:ss");
                    voucherInfo.AuthorizedFloor = multipleVoucher.AuthorizedFloor;
                    voucherInfo.AuthData = AuthData;
                    voucherDAL.AddVoucher(voucherInfo);
                }
            }

            return message;
        }

    }
}
